package com.cc8w.admin.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cc8w.shiro.ShiroRealm;
import com.cc8w.test.TestShiro;
import org.apache.commons.codec.binary.Base64;

import org.apache.jasper.tagplugins.jstl.core.Out;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.objenesis.instantiator.gcj.GCJInstantiator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.cc8w.admin.entity.AdminUserPojo;
import com.cc8w.admin.service.UserService;
import com.cc8w.util.VerifyCodeUtils;


@Controller
@RequestMapping("/sys/admin")
public class LoginController extends AdminBaseController  {
	private static Logger logger = Logger.getLogger(LoginController.class);

	//请检查上方contentType类型，如果想用springmvc @RequestBody注解做提交json字符串自动绑定到pojo入参时，类型需要是"application/json;charset=UTF-8"，否则会抛"not supported"异常。
	@Autowired
	@Qualifier("adminuserservice")
	private UserService userService;
	@Autowired
	private  SecurityManager securityManager;
	
	
	@RequestMapping("/login")
	public String Login() {

        
    	
 
        return "admin/sys/login";	
	}
	
	/**
	 * 提交登录(普通原始方式)
	 */
	@RequestMapping(value = "/dologin", method = RequestMethod.POST)
	public String doLogin(@RequestParam("username") String username,String password,String verifcode) {
		System.out.println(username);
		
		if( "".equals(username) || password =="" || verifcode=="")
		{
			System.out.println("没有填入");
		}
		String session_verif_code = (String) this.getRequest().getSession().getAttribute("verify_code");
		if("".equals(session_verif_code) || session_verif_code==null)
		{
			HashMap<String, String> obj = new HashMap<String, String>();
	        obj.put("title", "系统提示1");
	        obj.put("msg", "验证码不能为空");
	        obj.put("num", "10");
	        //obj.put("back_url", "http://www.baidu.com");
	        return this.jump( "common/jump", obj);
		}

		
		if(!session_verif_code.equals(verifcode)){
			System.out.println("验证码不正确");
			
	        HashMap<String, String> obj = new HashMap<String, String>();
	        obj.put("title", "系统提示1");
	        obj.put("msg", "验证码不正确");
	        obj.put("num", "10");
	        //obj.put("back_url", "http://www.baidu.com");
	       
	        return this.jump( "common/jump", obj);
	 		
		}
		
		
		//在数据库查询用户和密码
    	AdminUserPojo up = userService.getUserByName(username, password);

    	if(up!=null) {
    		this.getRequest().getSession().setAttribute("username", up.getUsername());
    		return "redirect:"+ this.basePath +"/admin/welcome/index"; //重定向跳转
    		
    	}
		
		
		
		return null;
	}

	/**
	 * 基于Shiro认证的登录
	 */
	@RequestMapping(value = "/doshirologin", method = RequestMethod.POST)
	public void doShiroLogin(@RequestParam("username") String username,String password,String verifcode){

		/* 全部交由Spring管理了

		//1.创建一个安全管理器的工厂
		//Factory<SecurityManager> factory = new IniSecurityManagerFactory();
		//2.在工厂中获取安全管理器
		//DefaultSecurityManager securityManager = (DefaultSecurityManager) factory.getInstance();

		//---添加认证凭证配置start  --如果Spring环境下(这些都是在xml配置的)
		//2.1 创建自定义Realm注入到安全管理器
		ShiroRealm shiroRealm = new ShiroRealm();//(SpringM在bean控制,并可以配置散列加密相关)
		//2.1.1设置密码学相关加密方式
		HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
		//2.1.2设置加密方式
		credentialsMatcher.setHashAlgorithmName("md5");
		//2.1.3设置散列次数
		credentialsMatcher.setHashIterations(1);
		//2.1.4将密码学凭证注入到自定义的Realm类中
		shiroRealm.setCredentialsMatcher(credentialsMatcher);
		//---添加认证凭证配置end  --如果Spring环境下(这些都是在xml配置的)

		securityManager.setRealm(shiroRealm);
		//3.将securityManager绑定到运行环境
		SecurityUtils.setSecurityManager(securityManager);

		 */

		//4.获取Subject对象(将要登录的用户)
		Subject subject = SecurityUtils.getSubject();
		//5.获取要登录用户的token,客户端传递过来的用户名和密码
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);

		//6.如果有记住我功能(设置参数)
		Integer rememberme = 1;
		if(null!=rememberme && rememberme==1){
			token.setRememberMe(true);//说明如果认证成功要记住我
		}

		try{
			//7.登陆(认证)
			subject.login(token);
			logger.info("登录了");

		}catch (IncorrectCredentialsException e ){
			logger.info("密码不正确");
			logger.info(e);
		}catch (UnknownAccountException e) {
			System.out.println("没有这个帐号");
		}catch (AuthenticationException e) {
			e.printStackTrace();
		}

	}
	
	
	/**
	 * 退出登录
	 */
	@RequestMapping("/outlogin")
	public String outLogin(HttpServletRequest request) {

		this.getRequest().getSession().setAttribute("username",null);
		return "redirect:"+ this.basePath +"sys/admin/login"; //重定向跳转(刷新)

	}
	
	/**
	 * 输出一个验证码(图片)
	 * @throws IOException 
	 */
	@RequestMapping("/verifcode")
	public void verifCode(HttpServletRequest request, HttpServletResponse response,Model model) throws IOException {
		
		//response.setContentType("text/html; charset=UTF-8");
        // 禁止图像缓存。
		response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        response.setContentType("image/jpeg");  
          
        //生成随机字串  
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);  
        //存入会话session  
        request.getSession().setAttribute("verify_code", verifyCode.toLowerCase());  
        Object vakue = request.getSession().getAttribute("verify_code");
        System.out.println(vakue);

        
        //生成图片  
        int width = 100;//宽
        int height = 40;//高  
        VerifyCodeUtils.outputImage(width, height, response.getOutputStream(), verifyCode);  
		//参数一：Image类对象 ,参数二：图片格式(非正式),
		//参数三：输出了（也可以是请求响应的response.getOutputStream().write(bytes),这样就输出到页面了）
		//ImageIO.write(verifyCode, "png", response.getOutputStream());

		response.getOutputStream().flush();
		response.getOutputStream().close();

		
		return;
		
	}
	/**
	 * 输出一个(图片)
	 * @throws IOException 
	 */
	
	@RequestMapping("/getimg")
	public void getImg(HttpServletRequest request, HttpServletResponse response,Model model) throws IOException {
		
		//response.setContentType("text/html; charset=UTF-8");
        // 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);

        response.setContentType("image/jpeg");
		//response.setContentType("image/png");

		//1.先试着读取图片，在输出
		
        String filePath = request.getServletContext().getRealPath("/");
        System.out.println(filePath);//项目路径
		File f = new File(filePath+"\\static\\images\\empty_order.png");
		//File f = new File(filePath+"\\static\\images\\IMG_9773.jpg");
		
		@SuppressWarnings("resource")
		InputStream is = new FileInputStream(f);
		

		String hexString = ""; 

		byte[] buf = new byte[1024*10];
		int len = 0;
		
		while((len=is.read(buf)) != -1) {
			System.out.println(len);		
			response.getOutputStream().write(buf);
	        //hexString += Convert.byte2Hexstr(buf);		
		}
	

		//byte[] bytes = Convert.hexstr2Byte(hexString);
		//response.getOutputStream().write(bytes);
	
		response.getOutputStream().flush();
		response.getOutputStream().close();
		is.close();
		
		//下载文本
//		response.addHeader("Content-Disposition","attachment;filename=image.png");		
		//输出文本
//		PrintWriter out = response.getWriter();
//		//out.write(sb.toString());
//		out.print(sb);
		
		return;
		
	}
	
	
}
